package com.lanou.fooddemo.fragment;

import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.lanou.fooddemo.R;
import com.lanou.fooddemo.activity.BasketActivity;
import com.lanou.fooddemo.activity.SameCityInformationActivity;
import com.lanou.fooddemo.adapter.SameCityListAdapter;
import com.lanou.fooddemo.bean.DataBean;
import com.lanou.fooddemo.bean.DetailBean;
import com.lanou.fooddemo.dao.FoodDatabaseTool;
import com.lanou.fooddemo.external.circularfloatingactionmenu.library.FloatingActionButton;
import com.lanou.fooddemo.external.circularfloatingactionmenu.library.FloatingActionMenu;
import com.lanou.fooddemo.external.circularfloatingactionmenu.library.SubActionButton;
import com.lanou.fooddemo.external.material_loading_progress_bar.CircleProgressBar;
import com.lanou.fooddemo.external.smart_image_view.SmartImageView;
import com.lanou.fooddemo.external.swipe_refresh_loading_layout.SwipeRefreshLoadingLayout;
import com.lanou.fooddemo.theme.FoodTheme;
import com.lanou.fooddemo.util.CommonUtil;
import com.lanou.fooddemo.util.NetUtil;
import com.lanou.fooddemo.view.FoodToast;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by LiuYan on 2015/8/6.
 */
public class SameCityFragment extends Fragment{
    private final String LOG_TAG = "SameCityFragment";

    /**
     * 传递给详细信息界面的Extra数据key
     */
    public static final String INFORMATION_KEY = "information";

    /**
     * 设置读取中dialog显示类型值
     */
    private final int TYPE_DIALOG_SHOW = 1;
    /**
     * 首次拉取数据的Message的类型值
     */
    private final int TYPE_GET_DATA = 2;
    /**
     * 非首次拉取数据的Message的类型值
     */
    private final int TYPE_GET_NEXT_DATA = 3;
    /**
     * 删除listItem视图更新数据的Message类型值
     */
    private final int TYPE_DELETE_LIST_ITEM = 4;

    private List<DataBean> dataBeans;
    private SameCityListAdapter adapter;

    /**
     * 定义list刷新进度条颜色
     */
    private int[] listColor = {android.R.color.holo_red_light, android.R.color.white,
            android.R.color.holo_red_light, android.R.color.holo_red_light};
    private Handler handler;

    /**
     * 数据ListView
     */
    private ListView listView;
    /**
     * 刷新布局
     */
    private SwipeRefreshLoadingLayout swipeRefreshLoadingLayout;
    /**
     * 读取中Dialog
     */
    private CircleProgressBar circleProgressBar;
    /**
     * 标题话题背景图片View
     */
    private SmartImageView sameCityImageView;
    /**
     * 标题话题主题内容
     */
    private TextView sameCityTitleTextView;
    /**
     * 标题话题副标题
     */
    private TextView sameCityDescTextView;
    /**
     * 悬浮菜单主按钮
     */
    private ImageView fabImageView;
    /**
     * 悬浮菜单按钮
     */
    private FloatingActionMenu floatingActionMenu;
    private SubActionButton subActionButtonOne;
    private SubActionButton subActionButtonTwo;
    private ImageView lookFoodImageView;
    private ImageView clearFoodImageView;

    private FoodDatabaseTool databaseTool;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        //通过LayoutInflater从layout布局中获得布局view
        View view = inflater.inflate(R.layout.fragment_same_city, null);
        //初始化控件
        initView(view);
        //首次进入获取数据
        getSameCityData(TYPE_GET_DATA);

        return view;
    }

    /**
     * 控件初始化方法
     * @param view 布局View
     */
    private void initView(View view) {
        listView = (ListView) view.findViewById(R.id.sameCityListView);
        swipeRefreshLoadingLayout =
                (SwipeRefreshLoadingLayout) view.findViewById(R.id.sameCitySwipeLayout);
        circleProgressBar = (CircleProgressBar) view.findViewById(R.id.sameCityProgressBar);
        sameCityImageView = (SmartImageView) view.findViewById(R.id.sameCityImageView);
        sameCityTitleTextView = (TextView) view.findViewById(R.id.sameCityTitleTextView);
        sameCityDescTextView = (TextView) view.findViewById(R.id.sameCityDescTextView);
        //设置读取中dialog显示
        circleProgressBar.setVisibility(View.VISIBLE);
        //初始化列表数据
        dataBeans = new ArrayList<DataBean>();
        //初始化列表适配器
        adapter = new SameCityListAdapter(getActivity(), dataBeans);
        //初始化数据库
        databaseTool = new FoodDatabaseTool(getActivity());
        //为listView绑定适配器
        listView.setAdapter(adapter);
        //为刷新布局添加进度条颜色
        swipeRefreshLoadingLayout.setColor(listColor[0], listColor[1],
                listColor[2], listColor[3]);
        //注册下拉刷新
        swipeRefreshLoadingLayout.setOnRefreshListener(new SwipeRefreshLoadingLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //获取首次拉取数据
                getSameCityData(TYPE_GET_DATA);
            }
        });
        //注册上拉加载更多
        swipeRefreshLoadingLayout.setOnLoadListener(new SwipeRefreshLoadingLayout.OnLoadListener() {
            @Override
            public void onLoad() {
                //加载更多数据
                getSameCityData(TYPE_GET_NEXT_DATA);
            }
        });
        //注册listView按下监听
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //创建跳转详细信息界面的Activity的Intent
                Intent intent = new Intent(getActivity(), SameCityInformationActivity.class);
                //获取列表相应点击位置的跳转信息
                DetailBean detailBean = dataBeans.get(position).getDetail();
                //将需要跳转的url携带信息传递到详细信息界面
                intent.putExtra(INFORMATION_KEY, detailBean.getApi());
                //跳转到详细信息界面
                startActivity(intent);
            }
        });
        //实例化Handler
        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                switch (msg.what) {
                    case TYPE_DELETE_LIST_ITEM :
                        //设置悬浮按钮动画
                        setFloatingActionButtonAnimation();
                        //加入菜篮子数据库
                        databaseTool.insertBasket(dataBeans.get(msg.arg1));
                        //移除数据
                        dataBeans.remove(msg.arg1);
                        FoodToast.makeText(getActivity(), "添加菜品成功", FoodToast.LENGTH_SHORT).show();
                        //如果数据为空了
                        if (dataBeans.isEmpty()) {
                            //设置开始加载更多效果
                            swipeRefreshLoadingLayout.setLoading(true);
                            //加载更多数据
                            getSameCityData(TYPE_GET_NEXT_DATA);
                        }
                        break;
                    case TYPE_DIALOG_SHOW :
                        //显示读取中dialog
                        circleProgressBar.setVisibility(View.VISIBLE);
                        break;
                    //处理首次进入和下拉刷新的数据更新
                    case TYPE_GET_DATA :
                        //清空dataBeans的List
                        dataBeans.clear();
                        //变量接收消息对象附带值
                        List<DataBean> firstDataBeans = (List<DataBean>) msg.obj;
                        //获取List中第一个话题栏DataBean
                        DataBean firstDataBean = firstDataBeans.get(0);
                        //设置话题栏图片背景
                        sameCityImageView.setImageUrl(firstDataBean.getPic().getUrl());
                        //设置话题栏主题内容
                        sameCityTitleTextView.setText(firstDataBean.getTitle());
                        //设置话题栏副标题内容
                        sameCityDescTextView.setText(firstDataBean.getDesc());
                        //去掉第一个话题栏Bean
                        firstDataBeans.remove(0);
                        //将msg中的数据全部填充到dataBeans
                        dataBeans.addAll(firstDataBeans);
                        //取消刷新状态
                        swipeRefreshLoadingLayout.setRefreshing(false);
                        //设置读取中进度条不显示
                        circleProgressBar.setVisibility(View.INVISIBLE);
                        break;
                    //处理加载更多的数据更新
                    case TYPE_GET_NEXT_DATA :
                        //将msg中的数据全部填充到dataBeans
                        dataBeans.addAll((List<DataBean>)msg.obj);
                        //取消加载更多状态
                        swipeRefreshLoadingLayout.setLoading(false);
                        //设置读取中进度条不显示
                        circleProgressBar.setVisibility(View.INVISIBLE);
                        break;
                }
                //通知适配器数据改变，更新视图
                adapter.notifyDataSetChanged();
                return true;
            }
        });
        //悬浮菜单创建显示
        foodMenuCreate();

        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                //设置长按动画
                CommonUtil.setListItemLongClickAnimation(getActivity(), view);
                //获取空消息
                Message msg = handler.obtainMessage();
                //设置消息类型
                msg.what = TYPE_DELETE_LIST_ITEM;
                //设置消息传递值
                msg.arg1 = position;
                //发送消息 间隔要比动画稍微小一些
                handler.sendMessageDelayed(msg, 2500);
                return true;
            }
        });
        setTheme();
    }

    @Override
    public void onResume() {
        super.onResume();
        setTheme();
    }

    /**
     * 获取同城数据
     * @param-url 获取数据的url
     * @param type 拉取类型，是刷新或首次拉取还是非首次拉取
     */
    private void getSameCityData(int type) {
        //实例化自定义Runable接口类SameCityRunable
        SameCityRunable sameCityRunable = new SameCityRunable(type);
        //将Runable实例类放入Thread构造方法,实例化线程
        Thread thread = new Thread(sameCityRunable);
        //开启线程
        thread.start();
    }
    private class SameCityRunable implements Runnable {

        /**
         * 读取中进度条显示消息
         */
        private Message msgDialogShow;
        /**
         * 数据传递消息
         */
        private Message msgData;
        /**
         * 首次拉取或非首次拉取类型
         */
        private int type;
        List<DataBean> runableDataBeanList = null;
        public SameCityRunable(int t) {
            type = t;
        }
        @Override
        public void run() {
            //从handler中获取消息赋给进度条显示消息
            msgDialogShow = handler.obtainMessage();
            //设置消息类型what值
            msgDialogShow.what = TYPE_DIALOG_SHOW;
            //发送进度条显示消息
            handler.sendMessage(msgDialogShow);
            //判断数据拉取类型，从不同接口拉取数据
            if (TYPE_GET_DATA == type) {
                runableDataBeanList = NetUtil.getDataBeanListDataForSameCityList();
            } else if (TYPE_GET_NEXT_DATA == type) {
                runableDataBeanList = NetUtil.getDataBeanListDataForSameCityListForNext();
            }

            if (CommonUtil.isListNotNull(runableDataBeanList)) {
                //从handler获取消息
                msgData = handler.obtainMessage();
                //设置消息what值
                msgData.what = type;
                //设置消息obj内容值
                msgData.obj = runableDataBeanList;
                //发送消息给handler
                handler.sendMessage(msgData);
            }
        }
    }

    /**
     * 创建悬浮菜单
     */
    private void foodMenuCreate() {
        Context c = getActivity();
        fabImageView = new ImageView(c);
        fabImageView.setImageResource(R.mipmap.basket);
        FloatingActionButton floatingActionButton = new FloatingActionButton.Builder(c)
                .setContentView(fabImageView)
                .build();


        ViewGroup.LayoutParams lp = floatingActionButton.getLayoutParams();

        SubActionButton.Builder subActionButtonBuilder = new SubActionButton.Builder(c);
        lookFoodImageView = new ImageView(c);
        clearFoodImageView = new ImageView(c);
        lookFoodImageView.setImageResource(R.mipmap.food_all);
        clearFoodImageView.setImageResource(R.mipmap.food_delete);

        subActionButtonOne = subActionButtonBuilder.setContentView(clearFoodImageView).build();
        subActionButtonOne.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                databaseTool.deleteAllBasket();
                FoodToast.makeText(getActivity(), "清空菜篮成功", FoodToast.LENGTH_SHORT).show();
            }
        });
        subActionButtonTwo = subActionButtonBuilder.setContentView(lookFoodImageView).build();
        subActionButtonTwo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), BasketActivity.class);
                startActivity(intent);
            }
        });

        floatingActionMenu = new FloatingActionMenu.Builder(c)
                .addSubActionView(subActionButtonOne)
                .addSubActionView(subActionButtonTwo)
                .attachTo(floatingActionButton)
                .build();

        floatingActionMenu.setStateChangeListener(new FloatingActionMenu.MenuStateChangeListener() {
            @Override
            public void onMenuOpened(FloatingActionMenu menu) {
                fabImageView.setRotation(0);
                PropertyValuesHolder propertyValuesHolder = PropertyValuesHolder.ofFloat(View.ROTATION,
                        -45);
                ObjectAnimator animator = ObjectAnimator.ofPropertyValuesHolder(fabImageView,
                        propertyValuesHolder);
                animator.start();
            }

            @Override
            public void onMenuClosed(FloatingActionMenu menu) {
                fabImageView.setRotation(-45);
                PropertyValuesHolder propertyValuesHolder = PropertyValuesHolder.ofFloat(View.ROTATION,
                        0);
                ObjectAnimator animator = ObjectAnimator.ofPropertyValuesHolder(fabImageView,
                        propertyValuesHolder);
                animator.start();
            }
        });
    }

    /**
     * 设置悬浮菜单隐藏
     * @param visible
     */
    public void setFloatingActionMenuVisible(int visible) {
        floatingActionMenu.setMenuVisible(visible);
    }

    /**
     * 设置悬浮菜单主按钮动画
     */
    public void setFloatingActionButtonAnimation() {
        floatingActionMenu.setFloatingActionMenuAnimation(getActivity());
    }

    /**
     * 设置主题
     */
    public void setTheme() {
        fabImageView.setImageResource(FoodTheme.getBasketMenu());
        lookFoodImageView.setImageResource(FoodTheme.getFoodAllMenu());
        clearFoodImageView.setImageResource(FoodTheme.getFoodDeleteMenu());
        listColor[0] = FoodTheme.getLoadingLayoutProcessColor();
        listColor[2] = FoodTheme.getLoadingLayoutProcessColor();
        listColor[3] = FoodTheme.getLoadingLayoutProcessColor();
        swipeRefreshLoadingLayout.setColor(listColor[0], listColor[1],
                listColor[2], listColor[3]);
        circleProgressBar.setColorSchemeResources(new int[]{FoodTheme.getCircleProgressBarColor()});
    }
}
